<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="书本名称" prop="bookName">
        <el-input
          v-model="queryParams.bookName"
          placeholder="请输入书本名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="书本成色" prop="bookLevel">
        <el-select v-model="queryParams.bookLevel" clearable size="small" placeholder="请选择书本成色">
          <el-option
            v-for="dict in dict.type.product_new_percent"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="书本类别" prop="bookType">
        <el-cascader placeholder="请选择书籍类别" 
          v-model="queryParams.bookType" 
          :options="categoryList" 
          :props="defaultBookTypeProps" 
          filterable clearable />
      </el-form-item>
      <el-form-item label="书本价格" prop="bookPrice">
        <el-row :span="12">
          <el-col :span="10">
            <el-input type="number"
              v-model="queryParams.minPrice"
              placeholder="请输入最低价"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-col>
          <el-col offset="1" :span="1">-</el-col>
          <el-col :span="10">
            <el-input type="number"
              v-model="queryParams.maxPrice"
              placeholder="请输入最高价"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-col>
        </el-row>
          
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:bookInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:bookInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:bookInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:bookInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="书本所属学生学号" align="center" prop="uid" />
      <el-table-column label="书本名称" align="center" prop="bookName" />
      <el-table-column label="书本成色" align="center" prop="bookLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_new_percent" :value="scope.row.bookLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="书本价格" align="center" prop="bookPrice" />
      <el-table-column label="书本类别" align="center" prop="bookTypeName" />
      <el-table-column label="书本数量" align="center" prop="bookCount" />
      <el-table-column label="交易方式" align="center" prop="transaction">>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_transaction_mode" :value="scope.row.transaction"/>
        </template>
      </el-table-column>
      <el-table-column label="上架状态" align="center" prop="status">
        <!-- <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template> -->
        <template slot-scope="scope">
          <dict-tag :options="dict.type.book_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status != 0"
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="handleBookUp(scope.row)"
            v-hasPermi="['product:bookInfo:up']"
          >上架</el-button>
          <el-button v-if="scope.row.status == 0"
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleBookDown(scope.row)"
            v-hasPermi="['product:bookInfo:up']"
          >下架</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:bookInfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:bookInfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    /> 

    <!-- 添加或修改书籍信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="上架学生学号" prop="uid">
              <el-input v-model="form.uid" min="0" type="number" placeholder="请输入上架此书本的学生id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="书本名称" prop="bookName">
              <el-input v-model="form.bookName" placeholder="请输入书本名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="书本成色" prop="bookLevel">
              <el-select v-model="form.bookLevel" placeholder="请选择书本成色">
                <el-option
                  v-for="dict in dict.type.product_new_percent"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="书本类别">
              <el-cascader placeholder="请选择书籍类别" 
              v-model="form.bookType" 
              :options="categoryList" 
              :props="defaultBookTypeProps" 
              filterable clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="书本价格" prop="bookPrice">
              <el-input v-model="form.bookPrice"  min="0" type="number" placeholder="请输入书本价格(0=私聊)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="书本原价" prop="bookOriginalPrice">
              <el-input v-model="form.bookOriginalPrice"  min="0" type="number" placeholder="请输入书本官方原价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="书本数量" prop="bookCount">
              <el-input v-model="form.bookCount" min="0" type="number" placeholder="请输入书本数量(默认为1)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易方式" prop="transaction">
              <el-select v-model="form.transaction" placeholder="请选择交易方式(默认为任意)">
                <el-option
                  v-for="dict in dict.type.product_transaction_mode"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="书籍图片集">
              <ImageUpload v-model="form.imageUrl"></ImageUpload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="书籍详细描述">
              <editor v-model="form.bookDesc" :min-height="192"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo, changeBookStatus, bookUp, bookDown } from "@/api/product/bookInfo";
import { listCategoryWithTree } from "@/api/product/category";
import ImageUpload from "@/components/ImageUpload/index";

export default {
  name: "Info",
  dicts: ['product_new_percent','product_transaction_mode','book_status'],
  components: { ImageUpload },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      bookNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 上架书籍信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        uid: null,
        bookName: null,
        bookLevel: null,
        bookPrice: null,
        minPrice: null,
        maxPrice: null,
        bookType: null,
        bookCount: null,
        transaction: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        uid: [
          { required: true, message: "上架此书本的学生学号不能为空", trigger: "blur" }
        ],
        bookName: [
          { required: true, message: "书本名称不能为空", trigger: "blur" }
        ],
        bookLevel: [
          { required: true, message: "书本成色不能为空", trigger: "blur" }
        ],
        bookPrice: [
          { required: true, message: "书本价格不能为空", trigger: "blur" }
        ],
        bookCount: [
          { pattern: /^([0-9]*)$/, message: "只能输入正整数", trigger: "blur" }
        ]
      },
      // 书籍分类表格数据
      categoryList: [],
      defaultBookTypeProps: {
        value: "id",
        label: "catName",
        children: "children",
        expandTrigger: "true",
        checkStrictly: "true"
      }
    };
  },
  created() {
    this.getList();
    this.loadingBookTypeTree();
  },
  methods: {
    /** 查询书籍信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        console.log(response);
        this.infoList = response.data.list;
        this.total = response.data.totalCount;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    }, 
    // 表单重置
    reset() {
      this.form = {
        id: null,
        uid: null,
        bookName: null,
        bookLevel: null,
        bookPrice: null,
        bookType: null,
        bookTypeName: null,
        bookCount: null,
        transaction: null,
        status: 0,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        desc: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      let qbt = this.queryParams.bookType;
      if(qbt != null && qbt instanceof Array){
        this.queryParams.bookType = qbt[qbt.length-1];
      }

      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.bookNames =  selection.map(item => item.bookName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 上架按钮 */
    handleBookUp(row){
      const ids = row.id;
      const bookName = row.bookName;
      this.$modal.confirm('是否确认上架 "' + bookName + '" 书籍？').then(function() {
        return bookUp(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("上架成功");
      }).catch(() => {});
    },
    /** 下架按钮 */
    handleBookDown(row){
      const ids = row.id;
      const bookName = row.bookName;
      this.$modal.confirm('是否确认下架 "' + bookName + '" 书籍？').then(function() {
        return bookDown(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("下架成功");
      }).catch(() => {});
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加书籍信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      console.log(id);
      getInfo(id).then(response => {
        // console.log(response);
        this.form = response.data;
        this.form.bookLevel = this.form.bookLevel + "";
        this.form.transaction = this.form.transaction + "";
        this.open = true;
        this.title = "修改书籍信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let fbt = this.form.bookType;
      if(fbt != null && fbt instanceof Array){
        this.form.bookType = fbt[fbt.length-1];
      }
      console.log(this.form);

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const bookNames = row.bookName || this.bookNames;
      this.$modal.confirm('是否确认删除名称为"' + bookNames + '"的书籍？').then(function() {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/bookInfo/export', {
        ...this.queryParams
      }, `二手书籍信息_${new Date().getTime()}.xlsx`)
    },
    // 书籍上架状态修改
    handleStatusChange(row) {
      let text = row.status === 0 ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '"书籍"' + row.bookName + '"吗？').then(function() {
        return changeBookStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === 0 ? 1 : 0;
      });
    },
    // 加载书籍类别的树形菜单
    loadingBookTypeTree(){
      listCategoryWithTree().then(response => {
        this.categoryList = response.data;
        this.categoryList.push({id:"0",catName:"暂无分类",catLevel:0,status:"0"})
        // console.log(response);
      });
    }
  }
};
</script>

<style>
  input::-webkit-inner-spin-button{ 
    -webkit-appearance: none !important;    
    margin: 0;    
    -moz-appearance: textfield; 
  }
</style>
